//
//  AlarmViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/1.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "AlarmViewController.h"

@interface AlarmViewController ()
{
    NSDictionary *_paramter;
    NSInteger _pageNum;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property (nonatomic ,strong)UITableView *tableView;
@property (nonatomic ,strong)NSMutableArray *dataSource;
@property (nonatomic ,strong)AFHTTPSessionManager *manager;

@end

@implementation AlarmViewController
- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"故障列表";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"seach_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(search)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *delegate = app.delegate;
    self.userId = delegate.userId;
    
    _dataSource = [[NSMutableArray alloc]init];

    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.rowHeight = 80;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    //v.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [self.tableView setTableFooterView:v];
    [self.view addSubview:_tableView];
//    _paramter = @{userid:[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",_pageNum]};
//    [self StartLoad];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [_dataSource removeAllObjects];
        _pageNum = 0;
        _paramter = @{userid:[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",_pageNum]};
        [self StartLoad];
    }];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNum = _pageNum + 1;
        _paramter = @{userid:[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",_pageNum]};
        [self StartLoad];
    }];

}
- (void)endRefresh{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)StartLoad{
    
    [_nothing removeFromSuperview];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_Alarm parameters:_paramter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        YYAlarmDataModel *dataModel = [[YYAlarmDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYAlarmListModel *model in dataModel.beanList) {

            [_dataSource addObject:model];
        }
        if (_dataSource.count == 0) {
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"没有故障信息"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500 ) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }

    }];
    
}
- (void)NothingRefresh:(UIButton *)sender{
    //[_nothing removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
    
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark-->tableviewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlarmTableViewCell *cell = nil;
    static NSString *reuse=@"cell";
    
    if (cell==nil) {
        cell = [[AlarmTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
    }
}
    //cell 的序号
   UILabel *number = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, 50, 50)];
    
    number.textColor = [UIColor whiteColor];
    number.textAlignment = NSTextAlignmentCenter;
        
    number.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    if ([number.text integerValue] > 100) {
        
        number.font = [UIFont systemFontOfSize:20];
    }else{
        number.font = [UIFont systemFontOfSize:40];
    }
    [cell addSubview:number];

    
    YYAlarmListModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}
//ios 9.0
/*
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    YYAlarmListModel *model = _dataSource[indexPath.row];
    if (model.state == 2) {
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前故障信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.findId == self.userId) {
                    [self delePlain:model.gzID];
                    //删除本地
                    [_dataSource removeObjectAtIndex:indexPath.row];
                    
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    [self showAlert:@"温馨提示" message:@"对不起!您没有权限删除这条信息" actionWithTitle:@"我知道了"];
                }
                
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
            
        }];
        return @[deleteRowAction];
    }else{
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前故障信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.findId == self.userId) {
                    [self delePlain:model.gzID];
                    //删除本地
                    [_dataSource removeObjectAtIndex:indexPath.row];

                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    [self showAlert:@"温馨提示" message:@"对不起!您没有权限删除这条信息" actionWithTitle:@"我知道了"];
                }
                
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];


        }];
        
        
        UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否对当前故障进行编辑" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.state == 0 && model.findId == self.userId) {
                    GZupdataViewController *gzup = [[GZupdataViewController alloc]init];
                    gzup.stationN = model.stationName;
                    gzup.faultTypeId = model.faultTypeId;
                    gzup.equipId = model.equipId;
                    gzup.GZtitle = model.name;
                    gzup.faultTypeName = model.faultTypeName;
                    gzup.stationId = model.stationId;
                    gzup.GZID = model.gzID;
                    gzup.discrib = model.discrib;
                    gzup.ocTime = model.time;
                    [self.navigationController pushViewController:gzup animated:YES];
                    
                }else if (model.state == 1 && model.changePsonId == self.userId){
                    GZshenpiVC *sh = [[GZshenpiVC alloc]init];
                    sh.faultApprovalId = model.faultApprovalId;
                    sh.Pid = [NSString stringWithFormat:@"%ld",model.gzID];
                    [self.navigationController pushViewController:sh animated:YES];
                }else{
                    [self showAlert:@"温馨提示" message:@"该故障您不能编辑" actionWithTitle:@"我知道了"];
                }
            
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
        }];
        moreRowAction.backgroundColor = UIColorFromRGB(0x2dd500);

        return @[moreRowAction,deleteRowAction];
    }
    
}
//控制哪些行可以移动
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//    YYAlarmListModel *model = _dataSource[indexPath.row];
//    
//    if (model.state == 0){
//        
//        return YES;
//    }else{
//        return NO;
//    }
    return YES;
}*/
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}



- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath



{
    
    return UITableViewCellEditingStyleDelete;
    
}



-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        
        
        
        //        [self.dataSourceremoveObjectAtIndex:indexPath.row];
        //
        //        [self.tableViewdeleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }
    
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    
    YYAlarmListModel *model = _dataSource[indexPath.row];
    if (model.state == 2) {
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前故障信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.findId == self.userId) {
                    [self delePlain:model.gzID];
                    //删除本地
                    [_dataSource removeObjectAtIndex:indexPath.row];
                    
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    [self showAlert:@"温馨提示" message:@"对不起!您没有权限删除这条信息" actionWithTitle:@"我知道了"];
                }
                
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
            
        }];
        return @[deleteRowAction];
    }else{
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前故障信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.findId == self.userId) {
                    [self delePlain:model.gzID];
                    //删除本地
                    [_dataSource removeObjectAtIndex:indexPath.row];
                    
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    [self showAlert:@"温馨提示" message:@"对不起!您没有权限删除这条信息" actionWithTitle:@"我知道了"];
                }
                
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
            
        }];
        
        
        UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否对当前故障进行编辑" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // NSLog(@"点击了知道了");
                //删除数据库
                //NSLog(@"%ld",model.gzID);
                if (model.state == 0 && model.findId == self.userId) {
                    GZupdataViewController *gzup = [[GZupdataViewController alloc]init];
                    gzup.stationN = model.stationName;
                    gzup.faultTypeId = model.faultTypeId;
                    gzup.equipId = model.equipId;
                    gzup.GZtitle = model.name;
                    gzup.faultTypeName = model.faultTypeName;
                    gzup.stationId = model.stationId;
                    gzup.GZID = model.gzID;
                    gzup.discrib = model.discrib;
                    gzup.ocTime = model.time;
                    [self.navigationController pushViewController:gzup animated:YES];
                    
                }else if (model.state == 1 && model.changePsonId == self.userId){
                    GZshenpiVC *sh = [[GZshenpiVC alloc]init];
                    sh.faultApprovalId = model.faultApprovalId;
                    sh.Pid = [NSString stringWithFormat:@"%ld",model.gzID];
                    [self.navigationController pushViewController:sh animated:YES];
                }else{
                    [self showAlert:@"温馨提示" message:@"该故障您不能编辑" actionWithTitle:@"我知道了"];
                }
                
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
        }];
        moreRowAction.backgroundColor = UIColorFromRGB(0x2dd500);
        
        return @[moreRowAction,deleteRowAction];
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    TroubleDetailVC *vc = [[TroubleDetailVC alloc]init];
    YYAlarmListModel *model = _dataSource[indexPath.row];
    vc.parameters = model.gzID;
    //NSLog(@"%ld",model.parameters);
    [self.navigationController pushViewController:vc animated:NO];
    
    
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)search{
    
    
    SearchViewController *search = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:search animated:YES];
    
}
/*
    列表删除指令
 */
- (void)delePlain:(NSInteger)faultId{
    
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:AlarmDeleterURL parameters:@{@"faultId":[NSString stringWithFormat:@"%ld",faultId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSSLog(@"%@",dic);
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSSLog(@"%@",error);
    }];
}
@end
